<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog v-if="crud.status.cu > 0" :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="520px">
        <el-form :key="'form' + isView()" ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-form-item label="站点名称" prop="name">
            <el-input v-model="form.name" v-viewinput="isView()" style="width: 370px;" :maxlength="100" :disabled="isView()" />
          </el-form-item>
          <el-form-item label="存储资源IP" prop="storeIp">
            <el-input v-model="form.storeIp" v-viewinput="isView()" style="width: 370px;" :maxlength="100" :disabled="isView()" />
          </el-form-item>
          <!--          <el-form-item label="服务器IP" prop="serverIp">
            <el-input v-model="form.serverIp" style="width: 370px;" :maxlength="100" :disabled="isView()" />
          </el-form-item>-->
          <el-form-item label="泛云IP" prop="fyIp">
            <el-input v-model="form.fyIp" v-viewinput="isView()" style="width: 370px;" :maxlength="100" :disabled="isView()" />
          </el-form-item>
          <el-form-item label="纵骥IP" prop="zjIp">
            <el-input v-model="form.zjIp" v-viewinput="isView()" style="width: 370px;" :maxlength="100" :disabled="isView()" />
          </el-form-item>
          <el-form-item label="站内企业" prop="dept">
            <treeselect
              ref="dept"
              v-model="deptIds"
              v-viewinput:multtreeselect="isView()"
              :disable-branch-nodes="true"
              :disabled="isView()"
              :multiple="true"
              :options="depts"
              :load-options="deptLoadDepts"
              style="width: 370px"
              :class="isView()?'treeColor':''"
              placeholder="请选择"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <div v-if="isView()">
            <el-button type="primary" @click="crud.cancelCU">关闭</el-button>
          </div>
          <div v-else>
            <el-button @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" stripe height="calc(100vh - 270px)" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column field="name" label="站点名称">
          <template v-slot="{ row }">
            <el-link type="primary" @click="hanleView(row.siteId)">{{ row.name }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="storeIp" label="存储资源IP" />
        <!--        <el-table-column prop="serverIp" label="服务器IP" />-->
        <el-table-column prop="fyIp" label="泛云IP" />
        <el-table-column prop="zjIp" label="纵骥IP" />
        <el-table-column prop="depts" label="站内企业" :formatter="formatDepts" />
        <el-table-column v-if="checkPer(['admin','site:edit','site:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudSite from '@/api/system/site'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import pagination from '@brotherCrud/Pagination'
import { getDepts, getDeptSuperiorSelf } from '@/api/system/dept'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const defaultForm = { siteId: null, name: null, storeIp: null, fyIp: null, zjIp: null, createBy: null, updateBy: null, createTime: null, updateTime: null, depts: null }
export default {
  name: 'Site',
  components: { pagination, crudOperation, udOperation, Treeselect },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '站点', url: 'api/site', idField: 'siteId', sort: 'siteId,desc', crudMethod: { ...crudSite }})
  },
  data() {
    const validateStoreIp = (rule, value, callback) => {
      if (value === null) {
        return callback(new Error('存储资源IP不能为空'))
      }
      const regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
      const valdata = value.split(',')
      let isCorrect = true
      if (valdata.length) {
        for (let i = 0; i < valdata.length; i++) {
          if (regexp.test(valdata[i]) === false) {
            isCorrect = false
          }
        }
      }
      if (!isCorrect) {
        callback(new Error('请输入正确的存储资源IP'))
      } else {
        callback()
      }
    }
    /*    const validateServerIp = (rule, value, callback) => {
      if (value == null) {
        return callback(new Error('服务器IP不能为空'))
      }
      const regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
      const valdata = value.split(',')
      let isCorrect = true
      if (valdata.length) {
        for (let i = 0; i < valdata.length; i++) {
          if (regexp.test(valdata[i]) === false) {
            isCorrect = false
          }
        }
      }
      if (!isCorrect) {
        callback(new Error('请输入正确的服务器IP'))
      } else {
        callback()
      }
    }*/
    const validateFyIp = (rule, value, callback) => {
      if (value === null && this.form.zjIp === null) {
        return callback(new Error('泛云IP和纵骥IP不能同时为空'))
      }
      // if (value && this.form.zjIp) {
      //   return callback(new Error('泛云IP和纵骥IP只能填一个'))
      // }
      let isCorrect = true
      if (value) {
        const regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
        const valdata = value.split(',')
        if (valdata.length) {
          for (let i = 0; i < valdata.length; i++) {
            if (regexp.test(valdata[i]) === false) {
              isCorrect = false
            }
          }
        }
      }
      if (!isCorrect) {
        callback(new Error('请输入正确的泛云IP'))
      } else {
        callback()
      }
    }
    const validateZjIp = (rule, value, callback) => {
      if (value === null && this.form.fyIp === null) {
        return callback(new Error('泛云IP和纵骥IP不能同时为空'))
      }
      // if (value && this.form.fyIp) {
      //   return callback(new Error('泛云IP和纵骥IP只能填一个'))
      // }
      let isCorrect = true
      if (value) {
        const regexp = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
        const valdata = value.split(',')
        if (valdata.length) {
          for (let i = 0; i < valdata.length; i++) {
            if (regexp.test(valdata[i]) === false) {
              isCorrect = false
            }
          }
        }
      }
      if (!isCorrect) {
        callback(new Error('请输入正确的纵骥IP'))
      } else {
        callback()
      }
    }
    const validateDept = (rule, val, callback) => {
      this.$nextTick(() => {
        if (!this.deptIds || this.deptIds.length <= 0) {
          callback(new Error('请选择站内企业'))
        } else {
          callback()
        }
      })
    }
    return {
      pageType: '', // 页面类型
      depts: [], // 站内企业
      deptIds: [], // 页面站内企业选中值
      permission: {
        add: ['admin', 'site:add'],
        edit: ['admin', 'site:edit'],
        del: ['admin', 'site:del'],
        download: ['admin', 'site:download']
      },
      rules: {
        name: [
          { required: true, message: '站点名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        storeIp: [
          { required: true, trigger: 'blur', validator: validateStoreIp },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        /*       serverIp: [
          { required: true, trigger: 'blur', validator: validateServerIp },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],*/
        fyIp: [
          { trigger: 'blur', validator: validateFyIp },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        zjIp: [
          { trigger: 'blur', validator: validateZjIp },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        dept: [
          { required: true, trigger: 'change', validator: validateDept }
        ]
      },
      queryTypeOptions: [
        { key: 'siteId', display_name: '站点ID' },
        { key: 'name', display_name: '站点名称' }
      ]
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form, type) {
      this.pageType = ''
      if (form.siteId === null) {
        this.getdept()
      } else {
        // 查看时
        if (type === 'view') {
          this.pageType = type
        }
        // this.deptIds = JSON.parse(form.depts)
        const deptIds = []
        if (form.depts.length > 0) {
          form.depts.map(item => {
            deptIds.push(item.id)
          })
          this.deptIds = deptIds
          this.getSupDepts(form.depts)
        } else {
          this.getdept()
        }
        return true
      }
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.deptIds = []
    },
    // 初始化编辑时候的设计软件
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.deptIds = []
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.deptIds) {
        // crud.form.depts = JSON.stringify(this.deptIds)
        const depts = []
        this.deptIds.forEach(item => {
          depts.push({ id: item })
        })
        crud.form.depts = depts
      }
    },
    getdept() {
      getDepts({ enabled: true, isExternal: false }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 站内企业
    getSupDepts(depts) {
      if (depts && depts.length > 0) {
        const deptId = []
        depts.map(item => {
          deptId.push(item.id)
        })
        getDeptSuperiorSelf(deptId).then(res => {
          const date = res.content
          this.buildDepts(date)
          let a = []
          a = this.form.depts
          if (date) {
            this.depts = date
            date.map(member => {
              if (member.children) {
                member.children.map(item => {
                  a.forEach(item2 => {
                    if (item.id === item2.id) {
                      item.isDisabled = true
                    }
                  })
                })
              } else {
                a.forEach(item2 => {
                  if (member.id === item2) {
                    member.isDisabled = true
                  }
                })
              }
              this.depts = date
            })
          }
        })
      }
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据 站内企业
    deptLoadDepts({ action, parentNode, callback }) {
      const that = this
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id, isExternal: false }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            // 站内企业编辑页新增过的不允许去掉
            const a = []
            if (that.form.depts && that.form.depts.length > 0) {
              that.form.depts.map(item => {
                a.push(item.id)
              })
            }
            if (that.crud.form.siteId !== null) {
              a.forEach(item2 => {
                if (obj.id === item2) {
                  obj.isDisabled = true
                }
              })
            } else {
              obj.isDisabled = false
            }
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 是否查看
    isView() {
      if (this.pageType === 'view') {
        return true
      } else {
        return false
      }
    },
    // 查看
    hanleView(siteId) {
      this.crud.data.map((item, index) => {
        if (item.siteId === siteId) {
          this.crud.toView(this.crud.data[index], 'view')
        }
      })
    },
    // 格式化站内企业
    formatDepts(row) {
      let dept = ''
      row.depts.forEach(item => {
        if (dept !== '') {
          dept = dept + '，' + item.name
        } else {
          dept = item.name
        }
      })
      return dept
    }
  }
}
</script>
